package com.knowif.service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Random;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.knowif.dao.TUserMapper;
import com.knowif.dao.UserCommentMapper;
import com.knowif.enumInfo.UserEnum;
import com.knowif.enumInfo.UserOrderStatusEnum;
import com.knowif.pojo.CommentPicture;
import com.knowif.pojo.TUser;
import com.knowif.pojo.Topic;
import com.knowif.pojo.TutorInfo;
import com.knowif.pojo.UserComment;
import com.knowif.pojo.UserCommentExample;
import com.knowif.pojo.UserCommentLabel;
import com.knowif.pojo.UserHelpful;
import com.knowif.pojo.UserOrder;
import com.knowif.search.SearchCondition;
import com.knowif.system.model.RestBean;
import com.knowif.util.commonUtil.IntegerUtil;

/**
 * @author xiehua
 * @Description: 用户评论dao服务层
 */
@Service
public class UserComment_service {

	@Autowired
	private UserCommentMapper userCommentMapper;

	@Autowired
	private CommentPicture_service commentPicture_service;

	@Autowired
	private UserCommentLabel_service userCommentLabel_service;

	@Autowired
	private UserOrder_service userOrder_service;

	@Autowired
	private TUserMapper tUserMapper;

	@Autowired
	private Tutor_service tutor_service;

	@Autowired
	private Topic_service topic_service;

	@Autowired
	private UserHelpful_service userHelpful_service;

	@Autowired
	private User_service user_service;

	/**
	 * 条件查询用户评论
	 * 
	 * @param userCommentExample
	 * @return
	 */
	public List<UserComment> selectUserComment(UserCommentExample userCommentExample) {
		if (userCommentExample == null) {
			return new ArrayList<UserComment>();
		}
		List<UserComment> userComments = userCommentMapper.selectByExample(userCommentExample);
		List<Integer> userCommentIds = UserComment.getIds(userComments);
		List<UserCommentLabel> userCommentLabels = userCommentLabel_service.getByCommentIds(userCommentIds);
		UserComment.saveUserCommentLabel(userComments, userCommentLabels);
		List<CommentPicture> commentPictures = commentPicture_service.getByCommentIds(userCommentIds);
		return UserComment.savePictures(userComments, commentPictures);
	}
	
	/**
	 * @author: xingyao 
	 * @Description:  通过导师id查看有多少用户评论了这个导师
	 * @param tutorId
	 * @return
	 */
	public int selectNumberBytutorId(Integer tutorId){
		if(IntegerUtil.isEmpty(tutorId)){
			return 0;
		}
		UserCommentExample commentExample = new UserCommentExample();
		commentExample.createCriteria().andTutorIdEqualTo(tutorId);
		return userCommentMapper.countByExample(commentExample);
	}
	

	/**
	 * @author: xingyao
	 * @Description: 查询更多的用户评论
	 * @param searchCondition
	 * @return
	 */
	public RestBean<?> selectMoreUserCommnet(SearchCondition searchCondition) {
		if (searchCondition == null) {
			return RestBean.buildError("请输入要查找的导师id");
		}
		// 先清理分页查询
		PageHelper.clearPage();
		// 通过导师id查找订单id

		int tutorId = (int) searchCondition.getContitionValue("tutorId");
		int userId = (int) searchCondition.getContitionValue("userId");
		PageHelper.startPage(searchCondition.getPageNumber(), searchCondition.getPageSize());

		if (IntegerUtil.isEmpty(tutorId)) {
			return RestBean.buildSuccess(null, 0);
		}
		List<UserComment> userComments = getBytutorId(tutorId);
		PageInfo<UserComment> pageInfo = new PageInfo<>(userComments);

		// 先清理分页查询
		PageHelper.clearPage();

		List<UserOrder> userOrders = getUserComment(userId, userComments);
		return RestBean.buildSuccess(userOrders, pageInfo.getTotal());
	}

	private List<UserComment> getBytutorId(int tutorId) {
		if (IntegerUtil.isEmpty(tutorId)) {
			return new ArrayList<UserComment>();
		}
		UserCommentExample userCommentExample = new UserCommentExample();
		userCommentExample.createCriteria().andTutorIdEqualTo(tutorId);
		List<UserComment> userComments = userCommentMapper.selectByExample(userCommentExample);
		return userComments;
	}

	public List<UserOrder> getUserComment(Integer userId, List<UserComment> userComments) {
		if (userComments == null || userComments.isEmpty()) {
			return new ArrayList<UserOrder>();
		}
		List<UserOrder> userOrders = userOrder_service.getByUserOrderIds(UserComment.getOrderIds(userComments));

		// 对订单通过时间进行排序
		Collections.sort(userOrders, UserOrder.userOrderComparator);

		// 判断该评论，该用户是否点赞了
		List<Integer> userCommentIds = UserComment.getCommendIds(userComments);
		List<UserHelpful> userHelpfuls = userHelpful_service.selectByCommentIds(userCommentIds);
		UserComment.saveHelpful(userId, userComments, userHelpfuls);

		List<Topic> topics = topic_service.selectTopic(UserOrder.getTopicIds(userOrders));
		userOrders = UserComment.saveTopics(topics, userOrders);

		List<TUser> tUsers = user_service.selectByUserIds(UserComment.getUserIds(userComments));
		userComments = UserComment.saveTUsers(userComments, tUsers);

		userOrders = UserOrder.saveComments(userOrders, userComments);
		return userOrders;
	}

	public List<UserComment> selectUserCommentByTutorId(Integer tutorId) {
		if (IntegerUtil.isEmpty(tutorId)) {
			return new ArrayList<UserComment>();
		}
		List<UserComment> userComments = getBytutorId(tutorId);
		List<Integer> userCommentIds = UserComment.getIds(userComments);
		List<CommentPicture> commentPictures = commentPicture_service.getByCommentIds(userCommentIds);
		return UserComment.savePictures(userComments, commentPictures);
	}

	public List<UserComment> selectUserCommentByOrderIds(List<Integer> orderIds) {
		if (orderIds == null || orderIds.isEmpty()) {
			return new ArrayList<UserComment>();
		}
		List<UserComment> userComments = getByUserOrderIds(orderIds);
		List<Integer> userCommentIds = UserComment.getIds(userComments);

		List<CommentPicture> commentPictures = commentPicture_service.getByCommentIds(userCommentIds);
		return UserComment.savePictures(userComments, commentPictures);
	}

	private List<UserComment> getByUserOrderIds(List<Integer> orderIds) {
		if (orderIds == null || orderIds.isEmpty()) {
			return new ArrayList<UserComment>();
		}
		UserCommentExample userCommentExample = new UserCommentExample();
		userCommentExample.createCriteria().andUserOrderIdIn(orderIds);
		List<UserComment> userComments = userCommentMapper.selectByExample(userCommentExample);
		return userComments;
	}

	/**
	 * 保存用户评论
	 * 
	 * @param userComment
	 * @return
	 */
	@Transactional
	public RestBean<?> saveUserComment(UserComment userComment) {
		if (userComment == null) {
			return RestBean.buildError("请填写评论信息");
		}
		if (isHaveComment(userComment.getUserOrderId(), userComment.getUserId(), userComment.getTutorId())) {
			return RestBean.buildError("订单已经评论");
		}
		userComment.setCreateTime(new Date());
		userCommentMapper.insert(userComment);
		commentPicture_service.insertAll(userComment.getCommentPictures(), userComment.getId());

		List<UserCommentLabel> userCommentLabels = userComment.getCommentLabels();
		for (int i = 0; userCommentLabels != null && i < userCommentLabels.size(); i++) {
			userCommentLabels.get(i).setUserCommentId(userComment.getId());
			userCommentLabels.get(i).setTutorId(userComment.getTutorId());
			userCommentLabels.get(i).setUserId(userComment.getUserId());
			userCommentLabel_service.insertUserCommentLabel(userCommentLabels.get(i));
		}
		// 更新用户订单的评分
		UserOrder userOrder = new UserOrder();
		userOrder.setStar(userComment.getStar());
		userOrder.setId(userComment.getUserOrderId());
		userOrder.setToUserId(userComment.getTutorId());
		if (userOrder.getStatus() != null && UserOrderStatusEnum.VIRTUAL.getState() != userOrder.getStatus()) {
			userOrder.setStatus(UserOrderStatusEnum.FINISH.getState());
		}
		userOrder_service.orderStar(userOrder);
		return RestBean.buildSuccess("添加用户评论成功");
	}

	@Transactional
	private RestBean<?> addUserVirtualComment(UserComment userComment) {
		if (userComment == null) {
			return RestBean.buildError("请填写评论信息");
		}
		if (isHaveComment(userComment.getUserOrderId(), userComment.getUserId(), userComment.getTutorId())) {
			return RestBean.buildError("订单已经评论");
		}
		userCommentMapper.insert(userComment);
		commentPicture_service.insertAll(userComment.getCommentPictures(), userComment.getId());

		List<UserCommentLabel> userCommentLabels = userComment.getCommentLabels();
		for (int i = 0; userCommentLabels != null && i < userCommentLabels.size(); i++) {
			userCommentLabels.get(i).setUserCommentId(userComment.getId());
			userCommentLabels.get(i).setTutorId(userComment.getTutorId());
			userCommentLabels.get(i).setUserId(userComment.getUserId());
			userCommentLabel_service.insertUserCommentLabel(userCommentLabels.get(i));
		}
		// 更新用户订单的评分
		UserOrder userOrder = new UserOrder();
		String starStr = userComment.getStar() + "";
		if (starStr != null) {
			char[] charStarts = starStr.toCharArray();
			if (charStarts != null && charStarts.length > 1) {
				userOrder.setStar(Integer.parseInt(charStarts[0]+""));
			}
		}
		userOrder.setId(userComment.getUserOrderId());
		userOrder.setToUserId(userComment.getTutorId());
		userOrder.setStatus(UserOrderStatusEnum.VIRTUAL.getState());
		userOrder_service.orderStar(userOrder);
		return RestBean.buildSuccess("添加用户评论成功");
	}


	private boolean isHaveComment(Integer orderId, Integer userId, Integer tutorId) {
		if (IntegerUtil.isEmpty(orderId) || IntegerUtil.isEmpty(userId) || IntegerUtil.isEmpty(tutorId)) {
			return false;
		}
		UserCommentExample userCommentExample = new UserCommentExample();
		userCommentExample.createCriteria().andTutorIdEqualTo(tutorId).andUserIdEqualTo(userId)
				.andUserOrderIdEqualTo(orderId);
		List<UserComment> userComments = userCommentMapper.selectByExample(userCommentExample);
		if (userComments == null || userComments.isEmpty()) {
			return false;
		} else {
			return true;
		}
	}

	/**
	 * 更新不为空的userComment属性
	 * 
	 * @param userComment
	 * @return
	 */
	public int updateUserCommentNotNull(UserComment userComment) {
		return userCommentMapper.updateByPrimaryKeySelective(userComment);
	}

	/**
	 * 删除userComment
	 * 
	 * @param userCommentId
	 */
	@Transactional
	public RestBean<?> deleteUserComment(Integer userCommentId) {
		if (userCommentId == null) {
			return RestBean.buildError("请选择要删除的用户评论");
		}
		userCommentMapper.deleteByPrimaryKey(userCommentId);
		commentPicture_service.deleteByCommentIds(userCommentId);
		return RestBean.buildSuccess("删除用户评论成功");
	}

	/**
	 * @author: xingyao
	 * @Description: 删除该用户的所有评论
	 * @param userId
	 * @return
	 */
	public RestBean<?> deleteByUserid(Integer userId) {
		if (userId == null) {
			return RestBean.buildError("请输入要删除的userId");
		}
		UserCommentExample userCommentExample = new UserCommentExample();
		userCommentExample.createCriteria().andUserIdEqualTo(userId);
		userCommentMapper.deleteByExample(userCommentExample);
		return RestBean.buildSuccess("删除成功");
	}

	/**
	 * @author: xingyao
	 * @Description: 批量删除
	 * @param userIds
	 * @return
	 */
	public RestBean<?> deleteByUserIds(List<Integer> userIds) {
		if (userIds == null) {
			return RestBean.buildError("请输入要删除的userId");
		}
		UserCommentExample userCommentExample = new UserCommentExample();
		userCommentExample.createCriteria().andUserIdIn(userIds);
		userCommentMapper.deleteByExample(userCommentExample);
		return RestBean.buildSuccess("删除成功");
	}

	/**
	 * @author: xingyao
	 * @Description: 添加虚拟评论功能
	 * @return
	 */
	@Transactional
	public RestBean<?> addVirtualComment(TUser tUser, TutorInfo tutorInfo, UserComment userComment) {
		if (tUser == null || tutorInfo == null || userComment == null) {
			return RestBean.buildError("请填写正确的信息");
		}
		tUser.setUserType(UserEnum.VIRTUAL_USER.getNumber());
		tUser.setOpenid("1");
		tUserMapper.insert(tUser);

		// 添加虚拟订单
		UserOrder userOrder = new UserOrder();
		userOrder.setUserId(tUser.getId());
		userOrder.setToUserId(tutorInfo.getId());
		userOrder.setStatus(UserOrderStatusEnum.VIRTUAL.getState());

		List<TutorInfo> tutorInfos = tutor_service.selectByUserId(tutorInfo.getId());
		if (tutorInfos == null || tutorInfos.isEmpty()) {
			return RestBean.buildError("请填写正确的导师ID");
		} else {
			tutorInfo = tutorInfos.get(0);
		}
		List<Topic> topics = topic_service.selectTopicByUserId(tutorInfo.getUserId());
		if (topics != null && !topics.isEmpty()) {
			String starStr = userComment.getStar() + "";
			if (starStr != null) {
				char[] charStarts = starStr.toCharArray();
				if (charStarts != null && charStarts.length >= 2) {
					if(Integer.valueOf(1)<0 || Integer.valueOf(1) > topics.size()){
						return RestBean.buildError("请填写正确的话题1---"+topics.size());
					}
					
					Topic topic = topics.get(Integer.parseInt(charStarts[1]+"")-1);
					userOrder.setTopicId(topic.getId());
				}
			}

		}
		Random random = new Random();
		userOrder_service.saveUserOrder(userOrder);
		userComment.setUserId(tUser.getId());
		userComment.setTutorId(tutorInfo.getUserId());
		userComment.setUserOrderId(userOrder.getId());
		// 随机生成0-50之间的随机数，用于显示是否有用
		userComment.setHelpfulCount(random.nextInt(50));
		// 添加虚拟评论
		addUserVirtualComment(userComment);
		return RestBean.buildSuccess("添加虚拟评论成功");
	}
}
